var Grid = require('./grid.js'); 
var Tile = require('./tile.js'); 
var GameManager = require('./game_manager.js');
Page({
  data: {
    grids: [],
    over: false,
    won: false,
    score: 0,
    highscore: 0,
    overMsg: '游戏结束'
  },
  onLoad: function () {
    this.GameManager = new GameManager(4);
    this.setData({
      grids: this.GameManager.setup(),// 游戏开始，随机生成数字单元格
      highscore: wx.getStorageSync('highscore') || 0
    });
  },
  onReady: function () {
  },
  onShow: function () {
    // 页面展示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  updateView: function (data) {
    if (data.over) {
      data.overMsg = '游戏结束';
    }
    if (data.won) {
      data.overMsg = '恭喜胜利！';
    }
    this.setData(data);
  },
  // 重新开始，重置数据
  restart: function () {
    this.updateView({  // 更新视图数据
      grids: this.GameManager.restart(),
      over: false,
      won: false,
      score: 0
    });
  },
  // 点触事件
  touchStartClienX: 0,
  touchStartClientY: 0,
  touchEndClientX: 0,
  touchEndClientY: 0,
  isMultiple: false, // 多手指操作
  touchStart: function (events) {//touchstart 手指触摸
    this.isMultiple = events.touches.length > 1;
    if (this.isMultiple) {
      return;
    }
    var touch = events.touches[0];
    this.touchStartClientX = touch.clientX;
    this.touchStartClientY = touch.clientY;
  },
  touchMove: function (events) {
    var touch = events.touches[0];
    this.touchEndClientX = touch.clientX;
    this.touchEndClientY = touch.clientY;
  },
  touchEnd: function (events) {
    if (this.isMultiple) {
      return;
    }
    var dx = this.touchEndClientX - this.touchStartClientX;
    var absDx = Math.abs(dx);//abs获取绝对值
    var dy = this.touchEndClientY - this.touchStartClientY;
    var absDy = Math.abs(dy);
    if (Math.max(absDx, absDy) > 10) {
      var direction = absDx > absDy ? (dx > 0 ? 1 : 3) : (dy > 0 ? 2 : 0);
      var data = this.GameManager.move(direction) || {// move：特定方向移动单元格
        grids: this.data.grids,
        over: this.data.over,
        won: this.data.won,
        score: this.data.score
      };
      var highscore = wx.getStorageSync('highscore') || 0;
      if (data.score > highscore) {
        wx.setStorageSync('highscore', data.score);
      }
      this.updateView({ 
        grids: data.grids,
        over: data.over,
        won: data.won,
        score: data.score,
        highscore: Math.max(highscore, data.score)
      });
    }
  }
});